<?php
class Exts_Models_Tags extends Exts_Db_Table_Abstract
{
    protected $_name = 'con_tags';
	protected $_primary = 'id';

	public function save( $type, $id, $tags  )
	{
        $tagsContentModel = new Exts_Models_TagsContents();
        $tagsContentModel->removeTags( $type, $id );

        $tags = explode( ',', $tags );

        if( ! count( $tags )) {
            return false;
        }

        foreach( $tags as $t ) {
            $row = $this->fetchRow( $this->select()->where('name=?', $t ) );
            if( ! count( $row ) ){
                $row = $this->createRow();
                $row->name = $t;
                $row->save();
            }
            $tagsContentModel->save( $type, $id, $row->id );
        }
        
	}
	
	
	/**
	 * Get All tags in array from a content
	 * @param string $type type content
	 * @param int $id id of content
	 * @return mixed $tags All tags of this content
	 */
	public function getTagsByContent( $type, $id )
	{
		$query = $this->getAdapter()->select()
			->from( array( 'tc' => 'con_tags_contents' ), array() )
			->join( array( 't' => 'con_tags' ), 't.id=tc.tag_id',array( 'name' ) )
			->where( 'tc.content_type=?', $type )
			->where( 'tc.content_id=?', $id );
			
		$rowset = $this->getAdapter()->fetchAll( $query );
		
		if( ! count( $rowset )) {
			return array();
		}
		$tags = array();
		foreach( $rowset as $tag ) {
			$tags[] = $tag;
		}
		return $tags;
	}
	
	public function getAsStr( $type, $id )
	{
		$bind = $this->getTagsByContent( $type, $id );
        
		if( count( $bind[0] )) {
			return implode( ",", $bind[0] );
		}
		return '';
		
	}
}